﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace KouDai.Phone.Helper
{
    public static class ExtensionsHelper
    {

        #region AsyncExtensions

        public static Task<WebResponse> GetResponseAsync(this WebRequest source)
        {
            return Task<WebResponse>.Factory.FromAsync(new Func<AsyncCallback, object, IAsyncResult>(source.BeginGetResponse), new Func<IAsyncResult, WebResponse>(source.EndGetResponse), null);
        }

        public static Task<Stream> GetRequestStreamAsync(this WebRequest source)
        {
            return Task<Stream>.Factory.FromAsync(new Func<AsyncCallback, object, IAsyncResult>(source.BeginGetRequestStream), new Func<IAsyncResult, Stream>(source.EndGetRequestStream), null);
        }

        public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<bool>();
            using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
            {
                if (task != await Task.WhenAny(task, tcs.Task))
                {
                    throw new OperationCanceledException(cancellationToken);
                }
            }
            return await task;
        }
        #endregion

        #region ObservableExtensions

        public static ObservableCollection<T> ToObservableCollection<T>(this List<T> list)
        {
            ObservableCollection<T> observableCollection = new ObservableCollection<T>();

            using (List<T>.Enumerator enumerator = list.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    T current = enumerator.Current;
                    observableCollection.Add(current);
                }
            }
            return observableCollection;
        }

        /// <summary>
        /// 将list 转换为 observablecollection
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="observables"></param>
        public static void ToObservableCollection<T>(this List<T> list,ObservableCollection<T> observables) 
        {
            foreach (T item in list)
            {
                observables.Add(item);
            }
        }

        #endregion

        #region GzipStreamExtensions
        public static bool IsCompressed(this WebResponse response)
        {
            //添加Gzip为空的操作
            return response.Headers["gzipType"] == null ? false : response.Headers["gzipType"].Equals("1");
        }
        #endregion
    }
}
